package com.taotao.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taotao.mapper.*;
import com.taotao.pojo.*;
import com.taotao.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.enums.OperateType;
import com.taotao.common.enums.OrderStatus;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.pojo.TransfersDto;
import com.taotao.common.utils.Constants;
import com.taotao.common.utils.DateUtil;
import com.taotao.common.utils.WechatpayUtil;
import com.taotao.common.wxpay.MyWXConfig;
import com.taotao.mapperCust.EyOrderMapperCust;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	EyOrderMapper eyOrderMapper;
	@Autowired
	EyAddressMapper eyAddressMapper;
	@Autowired
	EyOrderMapperCust eyOrderMapperCust;
	@Autowired
	WechatService wechatService;
	@Autowired
	ParamService paramService;
	@Autowired
	WechatPayService wechatPayService;
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyServiceMapper eyServiceMapper;
	@Autowired
	PictureService pictureService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	EySessionInfoMapper eySessionInfoMapper;
	
	BaseResult baseResult = new BaseResult();
	@Override
	public Map<String, Object> orderAdd(Map<String, String> map) {
		try {
			Map<String,String> returnMap=new HashMap<>();
			String outTradeNo=map.get("outTradeNo");  
			String memberId=map.get("memberId");
			String addressId = map.get("addressId");
			String goodsId = map.get("goodsId");
			String serviceId = map.get("serviceId");
			String transferId=map.get("transferId");
			String itemId = map.get("itemId");
			String ticketId = map.get("ticketId");
			String priceTotal = map.get("priceTotal");
			String priceDiscount = map.get("priceDiscount");
			String pricePay = map.get("pricePay");
			String remark = map.get("remark");
			String serviceDate = map.get("serviceDate");
			String serviceWeek = map.get("serviceWeek");
			String serviceTime = map.get("serviceTime");
			String modeType = map.get("modeType");
			
			if(StringUtils.isNotBlank(remark) && !wechatService.msgCheck(remark)){
				return baseResult.getErrorMap("The remark field is risky");
			}
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			if(member==null){
				return baseResult.getErrorMap("会员编号不存在,memberId:"+memberId);
			} 
			
			boolean insert=true;
			EyOrder order = new EyOrder();
			if(StringUtils.isBlank(transferId)){
				EyOrderExample example = new EyOrderExample();
				com.taotao.pojo.EyOrderExample.Criteria criteria = example.createCriteria();
				criteria.andMemberIdEqualTo(Integer.parseInt(memberId)); //当前的这个人 状态为待付款 的，做同一笔订单处理 更新
				criteria.andStatusEqualTo(OrderStatus.orderStatus_1.getCode());
				if(StringUtils.isNotBlank(goodsId)){
					criteria.andGoodsIdEqualTo(Integer.parseInt(goodsId));
					List<EyOrder> list= eyOrderMapper.selectByExample(example);
					if(list!=null && list.size()>0){
						order = list.get(0);
						insert=false;
					}
				}else if(StringUtils.isNotBlank(serviceId)){
					criteria.andServiceIdEqualTo(Integer.parseInt(serviceId));
					List<EyOrder> list= eyOrderMapper.selectByExample(example);
					if(list!=null && list.size()>0){
						order = list.get(0);
						insert=false;
					}
				}
			}

			order.setOutTradeNo(outTradeNo);
			order.setMemberId(Integer.parseInt(memberId));
			if(StringUtils.isNotBlank(addressId)){
				order.setAddressId(Integer.parseInt(addressId));
			}
			if(StringUtils.isNotBlank(goodsId)){
				order.setGoodsId(Integer.parseInt(goodsId));
			}
			if(StringUtils.isNotBlank(transferId)){
				order.setTransferId(Integer.parseInt(transferId));
			}
			if(StringUtils.isNotBlank(serviceId)){
				order.setServiceId(Integer.parseInt(serviceId));
			}
			if(StringUtils.isNotBlank(itemId)){
				order.setItemId(Integer.parseInt(itemId));
			}
			if(StringUtils.isNotBlank(ticketId)){
				order.setTicketId(Integer.parseInt(ticketId));
			}
			order.setPriceTotal(priceTotal);
			order.setPriceDiscount(priceDiscount);
			order.setPricePay(pricePay);
			order.setRemark(remark);
			order.setStatus(OrderStatus.orderStatus_1.getCode());//待付款
			
			order.setServiceDate(serviceDate);
			order.setServiceWeek(serviceWeek);
			order.setServiceTime(serviceTime);
			order.setModeType(modeType);
			order.setUpdateTime(DateUtil.getDateAndTime());
			
			if(insert){
				order.setCreateTime(DateUtil.getDateAndTime());
				eyOrderMapper.insert(order);
				operateLogService.insert(Integer.parseInt(memberId), null,null,OperateType.operateType_34.getDesc(),OperateType.operateType_34.getCode(),"");
			}else{
				eyOrderMapper.updateByPrimaryKey(order);
				operateLogService.insert(Integer.parseInt(memberId), null,null,OperateType.operateType_35.getDesc(),OperateType.operateType_35.getCode(),"");
			}
		
			returnMap.put("orderId", order.getId().toString());
			returnMap.put("outTradeNo", outTradeNo);
			
			
			return baseResult.getSuccMap(returnMap);
			
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}
	
	
	@Override
	public Map<String, Object> getSellOrderList(Map<String, String> map) {
		try {
			String pageNum=map.get("pageNum");
			String pageSize=map.get("pageSize");
			String memberId=map.get("memberId");
			String modeType=map.get("modeType");
			String currentTab=map.get("currentTab"); //查询订单状态
			Integer num=StringUtils.isBlank(pageNum)?Constants.pageNum:Integer.parseInt(pageNum);
			Integer size=StringUtils.isBlank(pageSize)?Constants.pageSize:Integer.parseInt(pageSize);
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			if(member==null){
				return baseResult.getErrorMap("会员编号不存在,memberId:"+memberId);
			}
			
			if(Constants.num_0.equals(currentTab)){ //0 是查询全部
				map.put("orderStatus", "");
			}else{
				map.put("orderStatus", currentTab);
			}

			String tencentCosEnable=paramService.getParam(Constants.tencent_cos_enable);
			PageHelper.startPage(num,size);
			List<Map> orderList = eyOrderMapperCust.getSellOrderList(map);
			for(Map m:orderList){
				String orderId=String.valueOf(m.get("orderId"));
				String updateTime=String.valueOf(m.get("updateTime"));
				String createTime=String.valueOf(m.get("createTime"));
				String status=String.valueOf(m.get("status"));
				String goodsId=String.valueOf(m.get("goodsId"));
				String serviceId=String.valueOf(m.get("serviceId"));
				String mId=String.valueOf(m.get("memberId"));
				
				if(StringUtils.isNotBlank(goodsId)){
					EyGoods goods = eyGoodsMapper.selectByPrimaryKey(Integer.parseInt(goodsId));
					String imageUrl = goods.getImageUrl();
					if(Constants.false_string.equals(tencentCosEnable)) {
						imageUrl=pictureService.changeDomain(imageUrl);
					}
					goods.setImageUrl(imageUrl);
					m.put("goods", goods);
				}
				
				if(StringUtils.isNotBlank(serviceId)){
					EyService service = eyServiceMapper.selectByPrimaryKey(Integer.parseInt(serviceId));
					String imageUrl = service.getImageUrl();
					if(Constants.false_string.equals(tencentCosEnable)) {
						imageUrl=pictureService.changeDomain(imageUrl);
					}
					service.setImageUrl(imageUrl);
					m.put("service", service);
				}
				
				EyMember memberInfo = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(mId));
				//如果设置了自己的头像，则使用自己的头像，
				if(StringUtils.isNotBlank(memberInfo.getImageUrl())){
					memberInfo.setAvatarUrl(memberInfo.getImageUrl());
				}
				m.put("member", memberInfo);
				updateTime=DateUtil.getDateTimeFormatStr(updateTime);
				m.put("updateTime", updateTime);
				createTime=DateUtil.getDateTimeFormatStr(createTime);
				m.put("createTime", createTime);
				String statusDesc=OrderStatus.getValue(status);
				m.put("statusDesc", statusDesc);
			}
			
			PageInfo<Map> pageInfo = new PageInfo<>(orderList);
	  		return baseResult.getSuccMap(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}
	
	
	@Override
	public Map<String, Object> getOrderList(Map<String, String> map) {
		try {
			String pageNum=map.get("pageNum");
			String pageSize=map.get("pageSize");
			String memberId=map.get("memberId");
			String modeType=map.get("modeType");
			String currentTab=map.get("currentTab");  //查询订单状态
			Integer num=StringUtils.isBlank(pageNum)?Constants.pageNum:Integer.parseInt(pageNum);
			Integer size=StringUtils.isBlank(pageSize)?Constants.pageSize:Integer.parseInt(pageSize);
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			if(member==null){
				return baseResult.getErrorMap("会员编号不存在,memberId:"+memberId);
			}
			
			if(Constants.num_1.equals(member.getIsAdmin())){ //管理员查询所有
				map.put("memberId", "");
			}
			
			if(Constants.num_0.equals(currentTab)){ //0 是查询全部
				map.put("orderStatus", "");
			}else{
				map.put("orderStatus", currentTab);
			}

			String tencentCosEnable=paramService.getParam(Constants.tencent_cos_enable);
			PageHelper.startPage(num,size);
			List<Map> orderList = eyOrderMapperCust.getOrderList(map);
			for(Map m:orderList){
				String orderId=String.valueOf(m.get("orderId"));
				String updateTime=String.valueOf(m.get("updateTime"));
				String createTime=String.valueOf(m.get("createTime"));
				String status=String.valueOf(m.get("status"));
				String goodsId=String.valueOf(m.get("goodsId"));
				String serviceId=String.valueOf(m.get("serviceId"));
				String mId=String.valueOf(m.get("memberId"));
				
				if(StringUtils.isNotBlank(goodsId)){
					EyGoods goods = eyGoodsMapper.selectByPrimaryKey(Integer.parseInt(goodsId));
					if(goods!=null){
						String imageUrl = goods.getImageUrl();
						if(Constants.false_string.equals(tencentCosEnable)) {
							imageUrl=pictureService.changeDomain(imageUrl);
						}
						goods.setImageUrl(imageUrl);
						m.put("goods", goods);
						String sessionKey=this.getSessionKey(goodsId,"",mId);
						m.put("sessionKey", sessionKey);
					}
				}
				
				if(StringUtils.isNotBlank(serviceId)){
					EyService service = eyServiceMapper.selectByPrimaryKey(Integer.parseInt(serviceId));
					if(service!=null){
						String imageUrl = service.getImageUrl();
						if(Constants.false_string.equals(tencentCosEnable)) {
							imageUrl=pictureService.changeDomain(imageUrl);
						}
						service.setImageUrl(imageUrl);
						m.put("service", service);
						String sessionKey=this.getSessionKey("",serviceId,mId);
						m.put("sessionKey", sessionKey);
					}
				}
				
				EyMember memberInfo = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(mId));
				//如果设置了自己的头像，则使用自己的头像，
				if(StringUtils.isNotBlank(memberInfo.getImageUrl())){
					memberInfo.setAvatarUrl(memberInfo.getImageUrl());
				}
				m.put("member", memberInfo);
				updateTime=DateUtil.getDateTimeFormatStr(updateTime);
				m.put("updateTime", updateTime);
				createTime=DateUtil.getDateTimeFormatStr(createTime);
				m.put("createTime", createTime);
				String statusDesc=OrderStatus.getValue(status);
				m.put("statusDesc", statusDesc);
			}
			
			PageInfo<Map> pageInfo = new PageInfo<>(orderList);
			return baseResult.getSuccMap(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}

	public String getSessionKey(String goodsId, String serviceId, String mId) {
		String sessionKey="";
		EySessionInfoExample example = new EySessionInfoExample();
		EySessionInfoExample.Criteria criteria = example.createCriteria();
		if(StringUtils.isNotBlank(goodsId)){
			criteria.andGoodsIdEqualTo(Integer.parseInt(goodsId));
		}
		if(StringUtils.isNotBlank(serviceId)){
			criteria.andServiceIdEqualTo(Integer.parseInt(serviceId));
		}
		criteria.andSenderEqualTo(Integer.parseInt(mId));
		List<EySessionInfo> sessionInfo = eySessionInfoMapper.selectByExample(example);
		if(sessionInfo!=null && sessionInfo.size()>0){
			sessionKey= sessionInfo.get(0).getSessionKey();
		}
		return sessionKey;
	}


	@Override
	public Map<String, Object> modifyOrder(Map<String, String> map) {
		try {
			String orderId=map.get("orderId");
			String outTradeNo=map.get("outTradeNo");  
			String memberId=map.get("memberId");
			String addressId = map.get("addressId");
			String goodsId = map.get("goodsId");
			String serviceId = map.get("serviceId");
			String itemId = map.get("itemId");
			String ticketId = map.get("ticketId");
			String priceTotal = map.get("priceTotal");
			String priceDiscount = map.get("priceDiscount");
			String pricePay = map.get("pricePay");
			String remark = map.get("remark");
			String serviceDate = map.get("serviceDate");
			String serviceWeek = map.get("serviceWeek");
			String serviceTime = map.get("serviceTime");
			String modeType = map.get("modeType");
			
			if(StringUtils.isNotBlank(remark) && !wechatService.msgCheck(remark)){
				return baseResult.getErrorMap("The remark field is risky");
			}
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			if(member==null){
				return baseResult.getErrorMap("会员编号不存在,memberId:"+memberId);
			} 
			
			EyOrder order = new EyOrder();
			order.setId(Integer.parseInt(orderId));
			order.setMemberId(Integer.parseInt(memberId));
			order.setAddressId(Integer.parseInt(addressId));
			order.setGoodsId(Integer.parseInt(goodsId));
			if(StringUtils.isNotBlank(serviceId)){
				order.setServiceId(Integer.parseInt(serviceId));
			}
			order.setItemId(Integer.parseInt(itemId));
			if(StringUtils.isNotBlank(ticketId)){
				order.setTicketId(Integer.parseInt(ticketId));
			}
			order.setPriceTotal(priceTotal);
			order.setPriceDiscount(priceDiscount);
			order.setPricePay(pricePay);
			order.setRemark(remark);
			
			order.setServiceDate(serviceDate);
			order.setServiceWeek(serviceWeek);
			order.setServiceTime(serviceTime);
			
			order.setUpdateTime(DateUtil.getDateAndTime());
			eyOrderMapper.updateByPrimaryKeySelective(order);
			
			operateLogService.insert(Integer.parseInt(memberId), null,null,OperateType.operateType_35.getDesc(),OperateType.operateType_35.getCode(),""); 
			
			return baseResult.getSuccMap();
			
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}


	@Override
	public Map<String, Object> deleteOrder(Map<String, String> map) {
		try {
			String orderId=map.get("orderId");
			String memberId=map.get("memberId");
			EyOrder order = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
			order.setStatus(Constants.num_100); //删除
			order.setUpdateTime(DateUtil.getDateAndTime());
			eyOrderMapper.updateByPrimaryKey(order);
			
			operateLogService.insert(Integer.parseInt(memberId), null,null,OperateType.operateType_36.getDesc(),OperateType.operateType_36.getCode(),""); 

			return baseResult.getSuccMap();
			
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}


	@Override
	@Transactional
	public Map<String, Object> modifyOrderStatus(Map<String, String> map) {
		String memberId=map.get("memberId");
		String orderId=map.get("orderId");
		String status=map.get("status");
		EyOrder order = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
		
		if(OrderStatus.orderStatus_3.getCode().equals(status)  && Constants.goods.equals(order.getModeType())){  //点击完成 goods类时买家点击，service类不用支付
			this.payToCharge(order);//付款到零钱
		}
		
		order.setStatus(status);
		order.setUpdateTime(DateUtil.getDateAndTime());
		eyOrderMapper.updateByPrimaryKey(order);
		
		operateLogService.insert(Integer.parseInt(memberId), null,null,OperateType.operateType_37.getDesc()+" status="+status,OperateType.operateType_37.getCode(),"");
		
		return baseResult.getSuccMap();
	}


	public void payToCharge(EyOrder order) {
			if(Constants.num_1.equals(order.getStatusObtain())){
				System.out.println("该订单平台已支付给卖家  orderId->"+order.getId());
				return;
			}
			
			Integer goodsId = order.getGoodsId();
			EyGoods goods = eyGoodsMapper.selectByPrimaryKey(goodsId);
			EyMember member=eyMemberMapper.selectByPrimaryKey(goods.getMemberId());
			
			double priceObtain;
			String pricePay = order.getPricePay();
			double pricePay_d = Double.parseDouble(pricePay);
			priceObtain=pricePay_d - pricePay_d*0.02;
			
	        order.setPriceObtain(String.valueOf(priceObtain)); //设置付款给卖家的金额
	        order.setStatusObtain(Constants.num_1); //平台已支付给卖家
			
			//付款给卖家
			String appkey = MyWXConfig.key;// 微信商户秘钥, 根据实际情况填写
	        String certPath = MyWXConfig.certPath;// 微信商户证书路径, 根据实际情况填写
	        TransfersDto model = new TransfersDto();// 微信接口请求参数, 根据实际情况填写
	        model.setMch_appid(MyWXConfig.appId); // 申请商户号的appid或商户号绑定的appid
	        model.setMchid(MyWXConfig.mchId); // 商户号
	        model.setMch_name("EasyGoEasyCome"); // 商户名称
	        model.setOpenid(member.getOpenId()); // 商户appid下，某用户的openid
	        model.setAmount(priceObtain); // 企业付款金额，这里单位为元
	        model.setDesc("企业付款到零钱");
	        System.out.println("请求参数->"+model.toString());
	        Map<String,String> resultMap = WechatpayUtil.doTransfers(appkey, certPath, model);
	        System.out.println("结果返回->"+resultMap.toString());
	        String result_code = resultMap.get("result_code");
	        if("FAIL".equalsIgnoreCase(result_code)){
	        	String err_code_des = resultMap.get("err_code_des");
	        }
	        operateLogService.insert(order.getMemberId(), null,null,resultMap.toString(),OperateType.operateType_43.getCode(),"");
	}


	@Override
	public Map<String, Object> getOrderInfo(Map<String, String> map) {
		try {
			String orderId = map.get("orderId");
			EyOrder orderInfo = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
			Integer addressId = orderInfo.getAddressId();
			EyAddress address = eyAddressMapper.selectByPrimaryKey(addressId);
			String showRefund="false";
			String createTime=orderInfo.getCreateTime();
			String beforeData=DateUtil.getDateAndTime(-15);
			if(createTime.compareTo(beforeData)>0){
				showRefund="true";
			}
			String updateTime = orderInfo.getUpdateTime();
			updateTime = DateUtil.getDateTimeFormatStr(updateTime);
			orderInfo.setUpdateTime(updateTime);

			String status = orderInfo.getStatus();
			orderInfo.setStatusDesc(OrderStatus.getValue(status));

			Map<String, Object> returnMap = new HashMap<String, Object>();
			returnMap.put("showRefund",showRefund);
			returnMap.put("address", address);
			returnMap.put("orderInfo", orderInfo);

			return baseResult.getSuccMap(returnMap);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}


	@Override
	public Map<String, Object> orderConfirm(Map<String, String> map) {
		String orderId = map.get("orderId");
		String isConfirm = map.get("isConfirm");
		EyOrder order = eyOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
		order.setIsConfirm(isConfirm);
		order.setUpdateTime(DateUtil.getDateAndTime());
		eyOrderMapper.updateByPrimaryKeySelective(order);
		return baseResult.getSuccMap(); 
	}

}
